/**
 * User: Obi
 * Date: 02.08.11
 * Time: 21:24
 */
package com.jediflasher.game_client.controller.world {
	import com.jediflasher.game_client.controller.BaseController;
	import com.jediflasher.game_client.data.world.CharacterData;
	import com.jediflasher.game_client.data.world.WorldData;
	import com.jediflasher.game_client.events.model.WorldDataEvent;
	import com.jediflasher.game_client.events.view.WorldViewEvent;
	import com.jediflasher.game_client.server.MessageWrapper;
	import com.jediflasher.game_client.server.ServerConnector;
	import com.jediflasher.game_client.server.messages.CharacterInfoRequest;
	import com.jediflasher.game_client.server.messages.CharacterMoveRequest;
	import com.jediflasher.game_client.server.messages.MessageType;
	import com.jediflasher.game_client.server.messages.MethodMovement;
	import com.jediflasher.game_client.server.messages.ServiceType;
	import com.jediflasher.game_client.view.world.WorldView;

	import flash.geom.Point;

	public class WorldController extends BaseController {

		public function WorldController(serverConnector:ServerConnector, data:WorldData, view:WorldView) {
			super(serverConnector, data, view);
			super._view.addEventListener(WorldViewEvent.CHARACTER_MOVE, this.handler_viewCharacterMove);

			this._worldData = data;
			this._worldData.addEventListener(WorldDataEvent.CHARACTER_ADDED, this.handler_modelCharacterAdded);
		}

		/**
		 * @private
		 */
		private var _worldData:WorldData;

		override protected function receiveMessage(messageWrapper:MessageWrapper):void {
			if (messageWrapper.serviceType != ServiceType.MOVEMENT) return;

			this._worldData.read(messageWrapper.message);
		}

		/**
		 * @private
		 */
		private function handler_viewCharacterMove(event:WorldViewEvent):void {
			var data:Point = event.data as Point;

			var moveMessage:CharacterMoveRequest = new CharacterMoveRequest();
			moveMessage.xPos = data.x;
			moveMessage.yPos = data.y;
			super.send(MessageType.REQUEST, ServiceType.MOVEMENT, MethodMovement.CHARACTER_MOVE, moveMessage, ServerConnector.getRequestId());
		}

		/**
		 * @private
		 */
		private function handler_modelCharacterAdded(event:WorldDataEvent):void {
			var character:CharacterData = event.data as CharacterData;

			var requestCharInfo:CharacterInfoRequest = new CharacterInfoRequest();
			requestCharInfo.characterId = character.id;
			super.send(MessageType.REQUEST, ServiceType.MOVEMENT, MethodMovement.CHARACTER_INFO, requestCharInfo);
		}
	}
}
